(function(jQuery, window, document, undefined) {
    function decodeUrl(encoded) {
        var src = decodeURIComponent(encoded);
        src = src.replace(/\+/g, " "); // "+" => " "
        return src;
    }

    function addLink(url, title, quality, type) {

        // format link html
        var template = '<a href="{0}" target="_blank">{1} [{2}] - {3}</a><br />';

        // url
        var linkHtml = template.replace(/\{0\}/g, url);

        // title
        title = title || url;
        linkHtml = linkHtml.replace(/\{1\}/g, title);

        // quality
        quality = quality || "Unknown Quality";
        linkHtml = linkHtml.replace(/\{2\}/g, quality);

        // type
        type = type || "Unknown Type";
        linkHtml = linkHtml.replace(/\{3\}/g, type);

        // add to page body
        var body = $(document).find("body");
        body.prepend(linkHtml);
    }
    
    var playerConfig = yt.playerConfig;
    var args = playerConfig.args;

    var url_encoded_fmt_stream_map = yt.playerConfig.args.url_encoded_fmt_stream_map;
    var streams = url_encoded_fmt_stream_map.split(",");
    var stream = streams[0];
    var streamDetails = stream.split("&");
    var params = {};
    jQuery.each(streamDetails, function(index, entry) {
        var separatorIndex = detail.indexOf("=");
        var key = entry.slice(0, separatorIndex);
        var value = entry.slice(separatorIndex + 1, entry.length);
        params[key] = value;
    });

    var encodedUrl = params.url;
    var url = decodeURIComponent(encodedUrl);

    // append signature
    var signature = params.sig;
    url += "&signature=" + signature;

    // append title
    var title = args.title;
    url += "&title=" + encodeURIComponent(title);
    console.log(url);

    // type
    var type = decodeUrl(params.type);
    console.log(type);

    // quality
    var quality = params.quality;

    // details
    var fmtList = args.fmt_list.split(",");
    var fmtDetails = {};
    jQuery.each(fmtList, function(index, fmtEntry) {
        var parts = fmtEntry.split("/");
        var itag = parts[0];
        var fmt = fmtDetails[itag] = {};
        fmt.resolution = parts[1];
        fmt.resolution = parts[2];
        fmt.resolution = parts[3];
        fmt.resolution = parts[4];
        

        params[key] = value;
    });

    : "46/1920x1080/99/0/0,37/1920x1080/9/0/115,45/1280x720/99/0/0,22/1280x720/9/0/115,44/854x480/99/0/0,35/854x480/9/0/115,43/640x360/99/0/0,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0,36/320x240/99/0/0,17/176x144/99/0/0",
    
    // add link to page
    addLink(url, title, quality, type);

}(jQuery, this, document));
